package dp01;

/**
 * 题目：地下城游戏
 * 题目链接：https://leetcode.cn/problems/dungeon-game/description/
 * dp[i][j] 状态表示从该点为起点，到终点所需最低初始血量
 * 状态转移方程：dp[i][j] = Math.min(dp[i][j+1],dp[i+1][j])-dungeon[i][j];
 */
public class Solution6 {
    public int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;
        int[][] dp = new int[m+1][n+1];
        for (int i = 0; i <= n; i++) {     //初始化最下面一行
            dp[m][i] = Integer.MAX_VALUE;
        }
        for (int i = 0; i <= m; i++) {
            dp[i][n] = Integer.MAX_VALUE;
        }
        dp[m][n-1] = dp[m-1][n] = 1;     //骑士解救完剩余必须大于0，那1即可
        for (int i = m-1; i >= 0 ; i--) {
            for (int j = n-1; j >= 0 ; j--) {
                dp[i][j] = Math.min(dp[i][j+1],dp[i+1][j])-dungeon[i][j];
                dp[i][j] = Math.max(1,dp[i][j]);    //防止dp[i][j]这里是一个超级大血包，结果为负值
            }
        }
        return dp[0][0];
    }
}
